<?php

namespace App\Http\Controllers\User;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Components\SmsComponent;

use DB;
use App\Models\UserModel;

use App\library\UtilFunction;

/**
 * 发送短信接口
 */
class SmsCheckCodeController extends UserController{

    public function __construct(){
        parent::__construct();        
    }

    /*版本控制，对应app版本跳转对应接口*/
    public function version_invoke(Request $request){
        $appversion = $request->input('appversion');
        $apptype = $request->input('apptype');
        if ($appversion && $apptype) {
            try{
                return $this->sms_check_code($request);
            }catch(\Exception $e){
                return $this->json('0','系统错误');
            }
        }else{
            return $this->json('102','该app版本下无此接口，请更新app');
        }
    }

    /**
     * 发送短信验证码
     * code_type login register change
     */
    public function sms_check_code(Request $request){
        $customAttr = [
            'phone' => '手机号',
            'code_type' => '验证方式',
        ];
        /*暂时不做校验*/
        $this->validate($request, [
            'phone' => 'required|numeric',
            'code_type' => 'required',
        ],[ ], $customAttr);

        $phone = $request->input('phone');
        $code_type = $request->input('code_type');

        if(!in_array($code_type,array('login','register','change'))){
            return $this->json('0','验证码类型有误!');
        }
        if($code_type=='register'){//如果是注册，验证该手机号是否已注册
            $user = UserModel::where('phone',$phone)->where("status",'!=',0)->first();
            if(!empty($user)){
                return $this->json('0','该手机号已注册');
            }
        }elseif($code_type=='change'){//更换手机号
            $user = UserModel::where('phone',$phone)->where("status",'!=',0)->first();
            if(!empty($user)){
                return $this->json('0','该手机号已注册');
            }
        }elseif($code_type == 'login'){
            $user = UserModel::where('phone',$phone)->where("status",'>',0)->first();
            if(empty($user)){
                return $this->json('0','您的手机号还没注册!',$phone);
            }
        }

        $sms = new SmsComponent();
        $sms_return = $sms->send_check_code($phone,$code_type);
        
        if($sms_return){
            return $this->json('1','验证码发送成功!');
        }else{
            return $this->json('0','发送失败!');
        }
    }
}
